package com.fary.controller;

import com.alibaba.excel.EasyExcel;
import com.fary.aop.service.AopService;
import com.fary.configuration.RequestJson;
import com.fary.excel.ExcelModel;
import com.fary.vo.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@Validated
@RestController
@RequestMapping("/")
public class ValidatorController {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private AopService aopService;

    @RequestMapping("/test")
    public Object test(@RequestJson String name) {
        System.out.println(name + ":");
        objectMapper.writer();
        return "OK";
    }

    // 1. 要校验的参数前，加上@Valid注解
    // 2. 紧随其后的，跟上一个BindingResult来存储校验信息
    @RequestMapping("/test1")
    public Object test1(@RequestBody @Valid User user) {
        // 如果检验出了问题，就返回错误信息
        // 这里我们返回的是全部的错误信息，实际中可根据bindingResult的方法根据需要返回自定义的信息。
        // 通常的解决方案为：JSR-303 + 全局ExceptionHandler
//        if (bindingResult.hasErrors()) {
//            return bindingResult.getAllErrors();
//        }
        return user;
    }

    @RequestMapping("/test2")
    public Object test2(@Valid User user) {
        return user;
    }

    @RequestMapping("/test3")
    public Object test3(@RequestBody User user) {
        return aopService.saveUser(user);
    }

    @PostMapping("/test4")
    public void download(@RequestBody User user) throws IOException {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), ExcelModel.class).sheet("模板").doWrite(data());
    }

    private List<ExcelModel> data() {
       return Arrays.asList(new ExcelModel("fangyuan", "28"));
    }
}
